package com.yellowpage.nsp.listener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TimerTask;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.servlet.ServletContextEvent;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.yellowpage.bigdata.data.NspOnofflogImeiDayregionSum;
import com.yellowpage.bigdata.service.AutoMailUserServiceImpl;
import com.yellowpage.bigdata.service.NspOnofflogImeiDayregionSumService;
import com.yellowpage.mail.bean.MailBean;
import com.yellowpage.mail.service.MailSendService;
import com.yellowpage.nsp.service.NspFetchLogService;
import com.yellowpage.white.common.Configuration;
import com.yellowpage.white.exception.MailSendException;

public class SynchroDataTimerTask extends TimerTask{
	private Configuration configuration;

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}
	 ServletContextEvent _e;
	    public SynchroDataTimerTask(ServletContextEvent e) {
	        _e = e;
	    }
	private List<NspOnofflogImeiDayregionSum> nspOnofflogImeiDayregionSumList = new ArrayList<NspOnofflogImeiDayregionSum>();
	private List<Map> resultList = new ArrayList<Map>();

	private NspOnofflogImeiDayregionSum nspOnofflogImeiDayregionSum;
	private NspOnofflogImeiDayregionSumService nspOnofflogImeiDayregionSumService;
	private MailSendService mailSendService;

	private String message;

	private String query_logDate;
	private String query_regionCode;
	private String query_logDate_end;
	
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		//ns.exportExcel2MailByAuto();
	//	System.out.println(ns);
		Map queryMap = new HashMap();
		Calendar calendar = new GregorianCalendar();  
		 calendar.set(Calendar.DAY_OF_MONTH, 1);  
	     Date times = calendar.getTime();
	     String logdate = new SimpleDateFormat("yyyyMMdd").format(times);
		Date time =new Date();
		String date = new SimpleDateFormat("yyyy-MM-dd").format(time);
		queryMap.put("logDate", logdate);
		queryMap.put("regionCode", "A");
		queryMap.put("query_logDate_end", query_logDate_end);
		WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(_e.getServletContext());
		nspOnofflogImeiDayregionSumService = (NspOnofflogImeiDayregionSumService) context.getBean("nspOnofflogImeiDayregionSumService");
		resultList = nspOnofflogImeiDayregionSumService
				.queryNspOnofflogImeiDayregionByPageAll(queryMap);
		//windows 下的测试环境
		 InputStream input = AutoMailUserServiceImpl.class.getClassLoader().getResourceAsStream("/constants.properties");
	        Properties prop=new Properties();
	        try {
				prop.load(input);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        String doc = prop.getProperty("MAIL_FOLDER");
	        String excelFile=doc+"/客户端统计_"+date+".xls";
		//liunx 下的测试环境
		 //  String excelFile="/xx/xx/客户端统计_"+date+".xls"; 
		FileOutputStream outp = null;
		try {
			outp = new FileOutputStream(excelFile);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}  
		try {
			//outp = response.getOutputStream();
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet sheet = workbook.createSheet("ImeiRegionAll");
			sheet.autoSizeColumn(1);
			HSSFCellStyle cellStyle = workbook.createCellStyle(); //单元格格式
			cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); //设置右边框
			cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
			
			HSSFRow row1 = sheet.createRow(0);// 二级标题栏
			String[] title = {"日期 ","活跃数","主动活跃数","被动（来显）","Android","IOS","累计用户数 ","新增数 "};
			for(int i = 0 ,len = title.length;i<len;i++){
				HSSFCell cell = row1.createCell(i);
				cell.setCellValue(title[i]);
			}
			for (int i = 0, len = resultList.size(); i < len; i++) {
				HSSFRow data_row = sheet.createRow(i + 1);
				Map result = resultList.get(i);
				data_row.createCell(0).setCellValue(
						result.get("LOG_DATE") != null ? result.get(
								"LOG_DATE").toString() : "");
				data_row.createCell(1).setCellValue(
						result.get("JHNUM") != null ? result.get("JHNUM")
								.toString() : "");
				data_row.createCell(2).setCellValue(
						result.get("ZDNUM") != null ? result.get("ZDNUM")
								.toString() : "");
				data_row.createCell(3).setCellValue(
						result.get("LXNUM") != null ? result.get("LXNUM")
								.toString() : "");
				data_row.createCell(4).setCellValue(
						result.get("ANDROIDNUM") != null ? result.get(
								"ANDROIDNUM").toString() : "");
				data_row.createCell(5).setCellValue(
						result.get("IOSNUM") != null ? result.get(
								"IOSNUM").toString() : "");
				data_row.createCell(6).setCellValue(
						result.get("ALLNUM") != null ? result.get(
								"ALLNUM").toString() : "");
				data_row.createCell(7).setCellValue(
						result.get("NEWNUM") != null ? result.get(
								"NEWNUM").toString() : "");
			}
			workbook.write(outp);
			//response.flushBuffer();
			outp.flush();
			//response.reset();
			
			
			System.out.println("正在发送邮件");
			InputStream in = SynchroDataTimerTask.class.getClassLoader().getResourceAsStream("/mail.properties");
	        Properties props=new Properties();
	        props.load(in);
	        in.close(); 
	        props.put("mail.smtp.host",props.getProperty("mail.host"));//发件人使用发邮件的电子信箱服务器我使用的是163的服务器
	        props.put("mail.smtp.auth",true); //这样才能通过验证
	        Session s=Session.getInstance(props);
	      //  s.setDebug(true);

	        MimeMessage message=new MimeMessage(s);
	        String ttitle = "客户端统计结果文件 _"+date;
	        String tcontent = "客户端统计结果文件 "+date;
	        List<String> userList = AutoMailUserServiceImpl.getUserList();
	        String tto = userList.get(0);
	        System.out.println("userList  :   "+userList);
	        String mess="附件为:"+logdate+" 日 至 昨日   的客户端统计结果文件，请查收，谢谢";
	        //给消息对象设置发件人/收件人/主题/发信时间
	        InternetAddress from=new InternetAddress(props.getProperty("mail.from"));  //发邮件的出发地（发件人的信箱），这是我的邮箱地址，使用请改成你的有效地址
	        message.setFrom(from);
			InternetAddress[] to=new InternetAddress[userList.size()];// tto为发邮件的目的地（收件人信箱）
			for (int i = 0; i < to.length; i++) {
				to[i]=new InternetAddress(userList.get(i));
			}
			message.setRecipients(Message.RecipientType.TO,to);
			message.setSubject(ttitle);// ttitle为邮件的标题
	        message.setSentDate(new Date());
	       // message.setText(mess);
	        BodyPart mdp=new MimeBodyPart();//新建一个存放信件内容的BodyPart对象
	        //mdp.setText(mess);
			mdp.setContent(tcontent,"text/html;charset=utf-8");//给BodyPart对象设置内容和格式/编码方式tcontent为邮件内容
	        Multipart mm=new MimeMultipart();//新建一个MimeMultipart对象用来存放BodyPart对
	        //象(事实上可以存放多个)
	        BodyPart bp = new MimeBodyPart();   
	        bp.setContent(mess,"text/html;charset=utf-8");   
	        mm.addBodyPart(bp);
	        FileDataSource fds=new FileDataSource(excelFile);
	        mdp.setDataHandler(new DataHandler(fds));
	        mdp.setFileName(MimeUtility.encodeText(fds.getName()));  //得到文件名同样至入BodyPart  
	        mm.addBodyPart(mdp);//将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
	        message.setContent(mm);//把mm作为消息对象的内容

	        message.saveChanges();
	        Transport transport=s.getTransport("smtp");
	        transport.connect(props.getProperty("mail.host"),props.getProperty("mail.userName"),props.getProperty("mail.password"));//发邮件人帐户密码,此外是我的帐户密码，使用时请修改。
	        transport.sendMessage(message,message.getAllRecipients());
	        transport.close();
			
			
		} catch (Exception e) {
		//	log.error(e.getMessage(), e);
			//this.addActionError("** 生成文件错误 !");
		}finally {
			if (outp != null) {
				try {
					outp.close();
				} catch (IOException e) {
					//log.error(e.getMessage(), e);
				}
			}
			File file = new File(excelFile);
			file.delete();
		}	
		}
	public void exportExcel2MailByAuto() {
		Map queryMap = new HashMap();
		Calendar calendar = new GregorianCalendar();  
		 calendar.set(Calendar.DAY_OF_MONTH, 1);  
	     Date times = calendar.getTime();
	     String logdate = new SimpleDateFormat("yyyyMMdd").format(times);
		Date time =new Date();
		String date = new SimpleDateFormat("yyyy-MM-dd").format(time);
		queryMap.put("logDate", logdate);
		queryMap.put("regionCode", "A");
		queryMap.put("query_logDate_end", query_logDate_end);
		resultList = nspOnofflogImeiDayregionSumService
				.queryNspOnofflogImeiDayregionByPageAll(queryMap);
		String excelFile="C:\\Users\\wxyu\\Desktop\\脚本\\日用户统计总览_"+date+".xls";  
		FileOutputStream outp = null;
		try {
			outp = new FileOutputStream(excelFile);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}  
		try {
			//outp = response.getOutputStream();
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet sheet = workbook.createSheet("ImeiRegionAll");
			sheet.autoSizeColumn(1);
			HSSFCellStyle cellStyle = workbook.createCellStyle(); //单元格格式
			cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); //设置右边框
			cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
			
			HSSFRow row1 = sheet.createRow(0);// 二级标题栏
			String[] title = {"日期 ","活跃数","主动活跃数","被动（来显）","Android","IOS","累计用户数 ","新增数 "};
			for(int i = 0 ,len = title.length;i<len;i++){
				HSSFCell cell = row1.createCell(i);
				cell.setCellValue(title[i]);
			}
			for (int i = 0, len = resultList.size(); i < len; i++) {
				HSSFRow data_row = sheet.createRow(i + 1);
				Map result = resultList.get(i);
				data_row.createCell(0).setCellValue(
						result.get("LOG_DATE") != null ? result.get(
								"LOG_DATE").toString() : "");
				data_row.createCell(1).setCellValue(
						result.get("JHNUM") != null ? result.get("JHNUM")
								.toString() : "");
				data_row.createCell(2).setCellValue(
						result.get("ZDNUM") != null ? result.get("ZDNUM")
								.toString() : "");
				data_row.createCell(3).setCellValue(
						result.get("LXNUM") != null ? result.get("LXNUM")
								.toString() : "");
				data_row.createCell(4).setCellValue(
						result.get("ANDROIDNUM") != null ? result.get(
								"ANDROIDNUM").toString() : "");
				data_row.createCell(5).setCellValue(
						result.get("IOSNUM") != null ? result.get(
								"IOSNUM").toString() : "");
				data_row.createCell(6).setCellValue(
						result.get("ALLNUM") != null ? result.get(
								"ALLNUM").toString() : "");
				data_row.createCell(7).setCellValue(
						result.get("NEWNUM") != null ? result.get(
								"NEWNUM").toString() : "");
			}
			workbook.write(outp);
			//response.flushBuffer();
			outp.flush();
			//response.reset();
			
			
			MailBean mail=new MailBean();
			mail.setUserName("zhoujiancai");
			mail.setPassWord("jamguitar335");
			
			
			mail.setFrom("zhoujiancai@besttone.com.cn");
			String mess="日用户统计总览;    统计周期:"+logdate+" 日 至 昨日 ;    详情见附件";
			System.out.println(mess);
			mail.setMessage(mess);
			mail.setSubject("日用户统计总览_"+date);
			mail.setTo("503940861@qq.com");
			
			List<String> attachmentList=new ArrayList<String>();
			attachmentList.add(excelFile);
			mail.setAttachmentList(attachmentList);
			//mail.setCc("szhou@guanghua.sh.cn");
			//mail.setBcc("szhou@guangua.sh.cn");
			try {
				mailSendService.sendMail(mail);
			} catch (MailSendException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
		} catch (Exception e) {
		//	log.error(e.getMessage(), e);
			//this.addActionError("** 生成文件错误 !");
		}finally {
			if (outp != null) {
				try {
					outp.close();
				} catch (IOException e) {
					//log.error(e.getMessage(), e);
				}
			}
		}
	}
	public List<NspOnofflogImeiDayregionSum> getNspOnofflogImeiDayregionSumList() {
		return nspOnofflogImeiDayregionSumList;
	}
	public void setNspOnofflogImeiDayregionSumList(
			List<NspOnofflogImeiDayregionSum> nspOnofflogImeiDayregionSumList) {
		this.nspOnofflogImeiDayregionSumList = nspOnofflogImeiDayregionSumList;
	}
	public List<Map> getResultList() {
		return resultList;
	}
	public void setResultList(List<Map> resultList) {
		this.resultList = resultList;
	}
	public NspOnofflogImeiDayregionSum getNspOnofflogImeiDayregionSum() {
		return nspOnofflogImeiDayregionSum;
	}
	public void setNspOnofflogImeiDayregionSum(
			NspOnofflogImeiDayregionSum nspOnofflogImeiDayregionSum) {
		this.nspOnofflogImeiDayregionSum = nspOnofflogImeiDayregionSum;
	}
	public NspOnofflogImeiDayregionSumService getNspOnofflogImeiDayregionSumService() {
		return nspOnofflogImeiDayregionSumService;
	}
	public void setNspOnofflogImeiDayregionSumService(
			NspOnofflogImeiDayregionSumService nspOnofflogImeiDayregionSumService) {
		this.nspOnofflogImeiDayregionSumService = nspOnofflogImeiDayregionSumService;
	}
	public MailSendService getMailSendService() {
		return mailSendService;
	}
	public void setMailSendService(MailSendService mailSendService) {
		this.mailSendService = mailSendService;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String getQuery_logDate() {
		return query_logDate;
	}
	public void setQuery_logDate(String query_logDate) {
		this.query_logDate = query_logDate;
	}
	public String getQuery_regionCode() {
		return query_regionCode;
	}
	public void setQuery_regionCode(String query_regionCode) {
		this.query_regionCode = query_regionCode;
	}
	public String getQuery_logDate_end() {
		return query_logDate_end;
	}
	public void setQuery_logDate_end(String query_logDate_end) {
		this.query_logDate_end = query_logDate_end;
	}
	public Configuration getConfiguration() {
		return configuration;
	}
	
	
}
